/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chess;

import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
 *
 * @author Alejandro
 */
public class Rook extends Token{
    
    public Rook (int column, int row, int color, JButton [][] board, 
            Token [][] tokens){
        ImageIcon[] iconos = {new ImageIcon("src/imagenes/Scourge/pudge-T50.gif")
                        ,new ImageIcon("src/imagenes/Legion/tiny-T50.gif")};
        this.setRow(row);
        this.setIcon(iconos);
        this.setColumn(column);
        this.setColor(color);
        this.board = board;
        this.colocarFicha();
        this.tokens = tokens;
        this.enemy = false;
        this.setType("R");
        this.setPass(true);
        
    }

    @Override
    public void moveToken(int newColumn, int newRow){
        int R = this.getRow();
        int C = this.getColumn();
        boolean hit = checkHit(newColumn, newRow, C, R);
        
        if ((newRow == R  || newColumn == C) && (!hit || enemy)){
            board[C][R].setIcon(null);
            this.setPass(false);
            this.setRow(newRow);
            this.setColumn(newColumn);
            this.colocarFicha();
            this.setCorrectMove(true);
        }
        else{
            this.setCorrectMove(false);
        }
        
    }
    
    private boolean checkHit(int newColumn, int newRow, int C, int R){
        int invertR = 0;
        int invertC = 0;
        if(newColumn == C){
            invertC = 0;
            if (newRow > R){
                invertR = 1;
            }
            else{
                invertR = -1;   
            }
        }
        if(newRow == R){
            invertR = 0;
            if (newColumn > C){
                invertC = 1;
            }
            else{
                invertC = -1;
            }
        }
        for (int i = 1; R + i*invertR != newRow + invertR ||
                C + i*invertC != newColumn + invertC; i++){
            if (tokens[C+i*invertC][R+i*invertR] != null){
                if (tokens[C+i*invertC][R+i*invertR] == tokens[newColumn][newRow] &&
                    tokens[newColumn][newRow].getColor() != this.getColor()){
                    enemy = true;
                }
                else{
                    enemy = false;
                }
                return true;
            }
        }
        return false;
    }   
    
    private void colocarFicha(){
        board[this.getColumn()][this.getRow()].setIcon(this.getIcon()[this.getColor()]);
    }
}
